<template>
  <div class="loginbody">
    <img src="../../assets/images/login/v2_rmaupk.jpg" class="bgImg" />
    <div class="logindata">
      <div class="loginImg">
        <img src="../../assets/images/login/v2_qpabld.png" />
      </div>
      <div class="loginInfo">
        <p class="loginTitle">族库管理系统</p>
      </div>
      <div class="formdata">
        <el-form ref="form" :model="form">
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              clearable
              placeholder="请输入账号"
              size="small"
              maxlength="16"
            >
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              clearable
              placeholder="请输入密码"
              show-password
              size="small"
              maxlength="16"
              @keyup.enter.native="login"
            >
              <i slot="prefix" class="el-input__icon el-icon-lock"></i
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="butt">
          <el-button
            type="primary"
            @click.native.prevent="login()"
            size="small"
            style="width: 100%"
            >登 录</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { CommonApi } from "@/api/managementCenter/projectManage/commonApi";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { Utility } from "@/libs/utility";
export default {
  name: "userLogin",
  data() {
    return {
      form: {
        // blogadmin
        password: "",
        username: "",
      },
      checked: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { max: 16, message: "不能大于16个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { max: 16, message: "不能大于16个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    if (localStorage.getItem("news")) {
      this.checked = true;
    }
    if (localStorage.getItem("userInfo")) {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.form.username = userInfo.username;
    }

    this.setPosition();
    /*窗口自适应，关键代码*/
    window.onresize = () => {
      this.setPosition();
    };
  },
  methods: {
    async getDiffTime() {
      const isTrue = await CommonApi.getTimeDiff();
      console.log(isTrue, "isTrue....................");
      if (isTrue) {
        PopupCommon.message(
          "error",
          "您当前电脑时间与服务器时间相差超过30秒，请调整时间！不调整将无法使用本系统！"
        );
      }
      return isTrue;
    },
    // 不管屏幕如何缩放，总保持1280的分辨率
    setPosition() {
      try {
        // 顶部菜单
        var globeHeader = document.getElementsByClassName("loginbody");
        globeHeader[0]["style"]["zoom"] = window.innerWidth / 1280;
      } catch (error) {
        console.log(error, "setPosition......");
      }
    },
    async login() {
      // 先去掉跟服务器去匹配时间的操作
      // const isTrue = await this.getDiffTime()
      // if (isTrue) {
      // 	return
      // }
      if (Utility.trimEmpty(this.form.username, true) == "") {
        PopupCommon.notify("info", "请填写用户名");
        return;
      }
      if (Utility.trimEmpty(this.form.password, true) == "") {
        PopupCommon.notify("info", "请填写密码");
        return;
      }
      let self = this;
      AjaxCommon("/api/Login/swgLogin", "post", {
        pwd: this.form.password,
        name: this.form.username,
      })
        .then((res) => {
          console.log(res, "res.......");
          if (res.data.result) {
            // 调用token接口 api/Login/Token?name=blogadmin&pass=blogadmin
            AjaxCommon(
              `/api/Login/JWTToken3.0?name=${this.form.username}&pass=${this.form.password}`,
              "get",
              null
            ).then((result) => {
              if (result.data.status == 200) {
                var token = result.data.response.token;
                var bear = result.data.response.token_type;
                AjaxCommon(
                  `/api/User/GetInfoByToken?token=${token}`,
                  "get",
                  null
                ).then((userItem) => {
                  console.log(userItem, "userItem.......");
                  var userId = userItem.data.response.uID;

                  // 根据用户id获取角色
                  AjaxCommon(
                    `/api/UserRole/GetRoleByUserId?userId=${userId}`,
                    "get",
                    null
                  ).then((u) => {
                    // u.data[0].Id=="0" 管理员
                    var userInfo = {
                      roleId: u.data[0].Id,
                      id: userId,
                      username: self.form.username,
                      realname: userItem.data.response.uRealName,
                      avatar:
                        "https://static.jeecg.com/temp/国炬软件logo_1606575029126.png",
                      token: bear + " " + token,
                    };
                    localStorage.setItem("userInfo", JSON.stringify(userInfo));
                    localStorage.setItem("token", userInfo.token);
                    sessionStorage.setItem("ALLMENULIST", "");
                    sessionStorage.setItem("menuInfo", "");
                    self.$router.push({
                      name: "mcIndex",
                    });
                  });
                });
                PopupCommon.notify("success", "登录成功");
              } else {
                PopupCommon.notify("error", "获取token失败");
              }
              console.log(result, self);
            });
          } else {
            PopupCommon.notify("error", "用户名或密码错误");
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    remenber(data) {
      this.checked = data;
      if (this.checked) {
        localStorage.setItem("news", JSON.stringify(this.form));
      } else {
        localStorage.removeItem("news");
      }
    },
  },
};
</script>

<style scoped>
.loginbody {
  width: 100%;
  height: 100%;
  position: relative;
}

.bgImg {
  width: 100%;
}

.logindata {
  z-index: 9;
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto;
  height: 236px;
  width: 408px;
  margin-left: 40%;
  background-color: #fff;
  box-shadow: #112138 2px 0px 20px 0px;
  border-radius: 10px;
}

.loginImg {
  width: 170px;
  height: 138px;
  float: left;
}

.loginImg img {
  display: block;
  width: 170px;
  height: 138px;
  margin-top: 50px;
  margin-left: 25px;
}

.loginInfo {
  float: right;
  height: 100%;
  width: 215px;
  text-align: left;
}

.loginInfo .loginTitle {
  font-family: SourceHanSansSC;
  font-weight: 700;
  font-size: 14px;
  color: rgb(40, 52, 67);
  font-style: normal;
  letter-spacing: 0px;
  margin-top: 40px;
  text-decoration: none;
}

.formdata {
  width: 200px;
  position: absolute;
  top: 73px;
  right: 11px;
  bottom: 20px;
}

.el-form-item {
  margin-bottom: 0;
}

.tool {
  display: flex;
  justify-content: space-between;
  color: rgba(38, 131, 253, 1);
}

.el-checkbox,
.el-checkbox__label {
  color: rgba(38, 131, 253, 1);
  font-size: 12px;
}

.butt {
  margin-top: 5px;
  margin-bottom: 10px;
  text-align: center;
}

.shou {
  cursor: pointer;
  color: rgba(38, 131, 253, 1);
  font-size: 12px;
}
</style>
